package com.pengpeng.advice.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.pengpeng.advice.result.R;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import springfox.documentation.oas.web.OpenApiControllerWebMvc;
import springfox.documentation.spring.web.plugins.Docket;
import springfox.documentation.swagger.web.ApiResourceController;

/**
 * @author 彭鹏
 * @date 2021/10/29.
 */
@RestControllerAdvice
public class HandleResponseAdvice implements ResponseBodyAdvice<Object> {
    @Autowired
    private ObjectMapper objectMapper;
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        //过滤swagger
        String className = returnType.getDeclaringClass().getName();
        String swaggerName = ApiResourceController.class.getName();
        String swaggerName2 = OpenApiControllerWebMvc.class.getName();
        return !swaggerName.equals(className)&& !swaggerName2.equals(className);
    }

    @SneakyThrows
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body == null) {
            return R.error();
        }
        //String类型需要特殊处理 手动转为json字符串
        if (body instanceof String) {
            return objectMapper.writeValueAsString(R.ok().data(body));
        }
        if (body instanceof R) {
            return body;
        }
        return R.ok().data(body);
    }
}
